<template class="firstpage">
    <div>
        <div class="boxMargin" style="margin: 20px 0;">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px" class="demo-ruleForm">
                <el-row>
                    <el-col :span="24">
                        <el-form-item  label="商品分类：" required>
                            <div style="display:inline-block;">
                                <el-select v-for="(arrItem,key) in customData.categroyList" v-model="customData.selectArr[key]" @focus="customData.position=key" @change="handleItemChange" :key="key" style="margin-right:10px;">
                                    <el-option v-for="item in arrItem" :value="item.categoryId" :key="item.categoryId" :label="item.categoryName"></el-option>
                                </el-select>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="货号：" prop="skuCode">
                            <el-input v-model="form.skuCode" class="w70"></el-input>
                            <el-button type="primary" size="small" style="display:inline-block" @click="onCopy">复制商品</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="商品条码：" prop="upCode">
                            <el-input v-model="form.upCode" class="w70"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="商品名称：" prop="goodsName">
                            <el-input v-model="form.goodsName" class="w70"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="商品副标题：">
                            <el-input v-model="form.goodsSubtitle" class="w70"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="商品简称：">
                            <el-input v-model="form.goodsSname" class="w70"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" style="display:flex;">
                        <el-form-item label="品牌：" prop="brandId">
                            <el-select v-model="form.brandId" placeholder="请选择" filterable remote reserve-keyword :remote-method="brandNameChange" :loading="customData.loading">
                                <el-option v-for="item in customData.brandNameList" :key="item.brandId" :label="item.brandName" :value="item.brandId"></el-option>
                            </el-select>
                        </el-form-item>&nbsp;&nbsp;&nbsp;
                        <el-checkbox v-model="customData.checked" style="margin-top:10px">前端不显示</el-checkbox>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="配送温度：">
                            <el-select v-model="form.keepTemperature" placeholder="请选择" clearable>
                                <el-option v-for="item in customData.keepTemperatureList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="宽：" prop="widthNum">
                            <el-input v-model="form.widthNum" class="w70" type="number">
                                <template slot="append">mm</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="高：" prop="heightNum">
                            <el-input v-model="form.heightNum" class="w70" type="number">
                                <template slot="append">mm</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="深：" prop="lengthNum">
                            <el-input v-model="form.lengthNum" class="w70" type="number">
                                <template slot="append">mm</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="商品重量：" prop="weightNum">
                            <el-input v-model="form.weightNum" class="w70" type="number">
                                <template slot="append">KG</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24" style="text-align: center;">
                        <el-form-item>
                            <el-button type="success" @click="infoCreate('form')">保存</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-dialog title="复制商品" :visible.sync="dialogData.isCopy" width="30%" center>
            <el-form  label-width="100px" class="demo-ruleForm">
            <el-row>
                <el-col :span="24">
                    <el-form-item  label="hostitem" required>
                        <el-input type="text" v-model="customData.copyNum" placeholder="请填写需要复制的商品hostitem"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="margin-top:10px"><el-col :span="24">确定复制后，除商品的“hostitem”、“hostUPC”以外的其他商品信息均覆盖当前商品！</el-col></el-row>
            <el-row style="text-align: right;margin-top:20px;">
                <el-button type="primary" size="small" @click="onSure">确定复制</el-button>
                <el-button plain size="small" @click="dialogData.isCopy=false;customData.copyNum=''">取消</el-button>
            </el-row>
         </el-form>
        </el-dialog>
    </div>
</template>
<script>
import $ from "jquery";
import _validate from "../../../../../framework/commonJs/wptx_validate";
import _tools from "../../../../../framework/commonJs/wptx_tools";
import _common from "../../../../../framework/commonJs/wptx_common";
import _allApi from "../../../../../framework/API/apiAll";
import _api from "../../../../../framework/API/generalItem";
let _FUNCTION_NAME = '';
export default {
    data() {
        return {
            tableData: [],
            searchData: {
            },
            searchDataBuffer: {
            },
            pageData: {
                pageNo: 1,
                pageSize: 10,
                total: 1,
                pageSizes: [10, 20, 50, 100]
            },
            dialogData: {
             isCopy: false
            },
            historyData: {},
            infoData: {},
            customData: {
                brandNameList:[],
                keepTemperatureList:[
                    { label: "请选择", value: '' },
                    { label: "冷藏(0-4℃)", value: '0' },
                    { label: "常温", value: '1' },
                    { label: "急冻(-18℃)", value: '2' }
                ],
                loading:false,
                categroyList:[],
                parentId:"",
                selectArr: [],
                position: null,
                versionId:"",
                itemId:"",
                hostUpc:"",
                copyNum: '',
                checked: false
            },
            form: {
            },
            rules: {
                skuCode:[
                    { required: true, validator: (rule, value, callback) => {
                        let reg = new RegExp("^[0-9]*$");
                        if (_validate.checkEmpty(value)) {
                            return callback(new Error('请输入HostItem'));
                        }else{
                            if (!reg.test(value)) {
                                return callback(new Error('只能输入数字'));
                            }
                        }
                        callback()
                    }, trigger: "blur" }
                ],
                upCode:[
                    { required: true, validator: (rule, value, callback) => {
                        let reg = new RegExp("^[0-9]*$");
                        if (_validate.checkEmpty(value)) {
                            return callback(new Error('请输入upCode'));
                        }else{
                            if (!reg.test(value)) {
                                return callback(new Error('只能输入数字'));
                            }
                        }
                        callback()
                    }, trigger: "blur" }
                ],
                goodsName:[
                    { required: true, message: "请输入商品名称", trigger: "blur" },
                ],
                brandId:[
                    { required: true, message: '请选择品牌', trigger: 'change' }
                ],
                widthNum:[
                    { required: true, message: "请输入宽", trigger: "blur" },
                ],
                heightNum:[
                    { required: true, message: "请输入高", trigger: "blur" },
                ],
                lengthNum:[
                    { required: true, message: "请输入深", trigger: "blur" },
                ],
                weightNum:[
                    { required: true, message: "请输入商品重量", trigger: "blur" },
                ],
                isPrecious:[
                    { required: true, message: '请选择是否贵重物品', trigger: 'change' }
                ],
                categoryId:[
                    { required: true, message: '请选择商品分类', trigger: 'change' }
                ]
            }
        };
    },
    computed: {},
    watch: {},
    filters: {},
    created() { },
    mounted() {
        this._FUNCTION_NAME = this.$route.name
        this.onInit()
    },
    beforeDestroy() { },
    methods: {
        onInit() {
            let self = this;
            let value = sessionStorage.getItem("itemId")
            if(_validate.checkEmpty(value)){
                self.previewCategory(); // 去请求分类
            }else{
                self.customData.itemId = sessionStorage.getItem("itemId")
                self.customData.itemVersionId = sessionStorage.getItem("versionId")
                self.onChangePage()
            }
        },
        onSearch(data) {
            let self = this;
        },
        onChangePage(data) {
            let self = this;
            let params = {
                itemId: self.customData.itemId,
                itemVersionId: self.customData.itemVersionId,
            }
            _api.infoDetail(self, params, self.callBack_infoDetail)
        },
        onReset(data) {
            let self = this;
        },
        onAdd(data) { },
        onDelete(data) {
            let self = this;
        },
        onInfo(data) {
            let self = this;
        },
        onUpdate(formName) {
            let self = this;
        },
        onBathDelete() {
            let self = this;
        },
        onBathUpdate() { },
        onDisable(data) {
            let self = this;
        },
        onEnable(data) {
            let self = this;
        },
        onUpload(data) { },
        onBathUpload() { },
        onExport(data) { },
        onDownload(data) { },
        onHistory(data) { },
        onSure () {
          let self = this, params = {skuCode: ''};
          if (_validate.checkKong(self.customData.copyNum)) {
            _validate.openTip(self, 'hostitem不可为空', 'warning');
            return false
          } else {
              params.skuCode = self.customData.copyNum;
            _api.itemOneCopy(self, params, self.callBack_itemOneCopy);
          }
        },
        // 详情
        callBack_infoDetail(data) {
            let self = this;
            if (_validate.checkEmpty(data)) {
                _validate.openTip(self, "详情数据加载超时，请刷新页面后重试", "warning");
            } else {
                self.form = data.data
                if(data.data.brandIsShow == 0){
                    self.customData.checked = true;
                } else {
                    self.customData.checked = false;
                }
                sessionStorage.setItem("categoryId", data.data.categoryId);
                if(!_validate.checkEmpty(data.data.brandId)){
                    self.brandNameChange(data.data.brandName)
                }
                self.previewCategory(data.data.categoryIds, data.data.categoryNames); // 去请求分类
                self.customData.hostUpc = _tools.commaTo(self.form.upCode)
            }
        },
        callBack_itemOneCopy (data) {
            let self = this;
            if (_validate.checkEmpty(data)) {
                _validate.openTip(self, "复制数据加载超时，请刷新页面后重试", "warning");
            } else {
                self.dialogData.isCopy = false;
                self.customData.copyNum = '';
                if(data.data.data.productType == 0){ // 普通商品
                 let routeUrl = self.$router.resolve({
                    path: "/samUpdate",
                    query: {
                        itemId: data.data.data.masterItemId,
                        itemVersionId: data.data.data.itemVersionId,
                        productType: data.data.data.productType,
                    }
                });
                window.close()
                window.open(routeUrl.href);
            }
            }
        },
        callBack_brandSelect(data){
            let self = this;
            if (_validate.checkEmpty(data)) {
                _validate.openTip(self, "品牌数据加载超时，请刷新页面后重试", "warning");
            } else {
                self.customData.loading = false;
                self.customData.brandNameList = data.data.result
            }
        },
        callBack_initCategoryCascade(data, idList, index){
            let self = this;
            if (_validate.checkEmpty(data)) {
                _validate.openTip(self, "分类数据加载超时，请刷新页面后重试", "warning");
            } else {
                if(_validate.checkEmpty(index)){
                    self.customData.categroyList = [];
                    self.customData.categroyList.push(data.data);
                    self.customData.selectArr = [];
                    return;
                }else{
                    if(_validate.checkListEmpty(idList)){
                        if(index == 0 || data.data.length != 0){
                            self.customData.categroyList.splice(index + 1, self.customData.categroyList.length, data.data);
                            self.customData.selectArr.splice(index + 1, self.customData.selectArr.length);
                        }
                        if(data.data.length == 0){
                            self.customData.categroyList.splice(index + 1, self.customData.categroyList.length);
                            self.customData.selectArr.splice(index + 1, self.customData.selectArr.length);
                        }
                    }else{
                        _tools.info("-->级联处理["+index+"]级分类");
                        self.customData.categroyList[index] = data.data  // 将刚刚的默认渲染的一条数据所对应的位置 换成 后台给的数据
                        index ++;
                        if(index >= idList.length){  // 当 处理到最后一级时  直接退出
                            return;
                        }
                        let currId = idList[index - 1];
                        self.initCategoryList(idList, currId, index);
                    }
                }
            }
        },
        callBack_infoCreate(data){
            let self = this;
            if (_validate.checkEmpty(data)) {
                _validate.openTip(self, "新增超时，请稍后重试", "warning");
            } else {
                _validate.openTip(self, "新增成功", "success");
                self.customData.itemId = data.data.itemId
                self.customData.versionId = data.data.versionId
                sessionStorage.setItem("itemId", data.data.itemId);
                sessionStorage.setItem("versionId", data.data.versionId);
                sessionStorage.setItem("categoryId", self.form.categoryId);
            }
        },
        // 更新
        callBack_infoUpdate(data){
            let self = this;
            if (_validate.checkEmpty(data)) {
                _validate.openTip(self, "更新超时，请稍后重试", "warning");
            } else {
                _validate.openTip(self, "修改成功", "success");
                sessionStorage.setItem("categoryId", self.form.categoryId);
            }
        },
        brandNameChange(query){
            let self = this;
            if (!_tools.blankSpace(query)) {
                self.customData.loading = true;
                let params = {
                    brandName:query
                }
                setTimeout(function(){
                    _allApi.brandSelect(self, params,self.callBack_brandSelect)
                },1000);
            } else {
                self.customData.brandNameList = [];
            }
        },
        handleItemChange(e) {
            let self = this;
            let current = e;//获取选中值(实际项目可通过此值调接口获取下一级选项)
            self.form.categoryId = current
            self.initCategoryList(null, current, self.customData.position);
        },
        infoCreate(formName){
            let self = this;
            if(_validate.checkEmpty(self.form.categoryId)){
                _validate.openTip(self, "请选择商品分类", "warning");
                return
            }
            let params = self.form
            for (let i = 0; i < self.customData.brandNameList.length; i++) {
                if(self.customData.brandNameList[i].brandId == self.form.brandId){
                    params.brandName = self.customData.brandNameList[i].brandName
                }
            }
            self.$refs[formName].validate((valid) => {
                if (valid) {
                    if (self.customData.checked == true) {
                      params.brandIsShow = 0;
                    } else {
                      params.brandIsShow = 1;
                    }
                    if(_validate.checkEmpty(self.customData.itemId)){
                        _api.infoCreate(self,params,self.callBack_infoCreate)
                    }else{
                        params.itemId = self.customData.itemId
                        _api.infoUpdate(self,params,self.callBack_infoUpdate)
                    }
                } else {
                    return false;
                }
            });
        },
        hostUpcChange(value){
            let self = this;
            self.customData.hostUpc = self.customData.hostUpc.replace(/[^\r\n0-9]/g,'');
            self.form.upCode = _tools.enter(self.customData.hostUpc)
        },
        previewCategory(idList, nameList){
            let self = this;
            if(_validate.checkListEmpty(idList)){
                // 未选择一级分类，初始化一级分类，且设置成请选择
                self.initCategoryList();
            } else {
                if(idList.length != nameList.length){
                    // id与name长度不等 只请求一级分类 并设置成已选择
                    self.initCategoryList();
                }else{
                    // 已选择一级分类，还原现有分类
                    self.customData.selectArr = idList
                    // 默认将 已选的分类展示出来 以防后台给的数据有问题
                    self.initPreviewCategoryList(idList, nameList);
                    // 级联查询 传index为0 下标开始
                    self.initCategoryList(idList, "", 0);
                }
            }
        },
        initPreviewCategoryList(idList, nameList){
            let self = this;
            let currId;
            let currName;
            let parentId;
            let isLeaf;
            for(let cnt = 0 ; cnt < idList.length ; cnt ++){
                currId = idList[cnt];
                currName = nameList[cnt];
                if(cnt == 0){
                    parentId = "";
                }else{
                    parentId = idList[cnt-1];
                }
                if(cnt == idList.length - 1){
                    isLeaf = 1;
                }else{
                    isLeaf = 0;
                }
                let categoryInfo = {
                    "categoryId":currId,
                    "categoryName":currName,
                    "parentId":parentId,
                    "isLeaf":isLeaf,
                    "categoryLevel":(cnt+1)
                }
                let categoryList = [];
                categoryList.push(categoryInfo);
                self.customData.categroyList.push(categoryList);
            }
        },
        initCategoryList(idList, currId, index){
            let self = this;
            let data = {
                parentId:currId
            }
            _allApi.categroyCascade(self,data, self.callBack_initCategoryCascade, idList, index)
        },
        onCopy () {
            let self = this;
            self.dialogData.isCopy = true;
        }
    }
};
</script>
<style scoped>
.w70{
    width: 70%;
}
</style>
